package com.lyj.stuelasticsearch.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.lyj.stuelasticsearch.entity.Product;
import com.lyj.stuelasticsearch.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    ElasticsearchClient elasticsearchClient;

    // 使用新客户端示例
    public SearchResponse<Product> complexSearch() throws IOException {
        return elasticsearchClient.search(s -> s
                        .index("products")
                        .query(q -> q
                                .match(t -> t
                                        .field("name")
                                        .query("phone")
                                )
                        ),
                Product.class
        );
    }

    // 保存或更新
    public Product save(Product product) {
        return productRepository.save(product);
    }

    // 批量保存
    public Iterable<Product> saveAll(List<Product> products) {
        return productRepository.saveAll(products);
    }

    // 根据ID查询
    public Product findById(String id) {
        return productRepository.findById(id).orElse(null);
    }

    // 查询所有
    public Iterable<Product> findAll() {
        return productRepository.findAll();
    }

    // 分页查询
    public Page<Product> findAll(int page, int size) {
        return productRepository.findAll(PageRequest.of(page, size));
    }

    // 根据名称查询
    public List<Product> findByName(String name) {
        return productRepository.findByName(name);
    }

    // 根据价格范围查询
    public List<Product> findByPriceBetween(Double min, Double max) {
        return productRepository.findByPriceBetween(min, max);
    }

    // 根据分类查询
    public List<Product> findByCategory(String category) {
        return productRepository.findByCategory(category);
    }

    // 删除
    public void delete(Product product) {
        productRepository.delete(product);
    }

    // 根据ID删除
    public void deleteById(String id) {
        productRepository.deleteById(id);
    }
}